package com.azzcs.parse;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @Author: wzg
 * @Date: 2020/12/6 上午11:15
 */
public class XMLMapperStatementBuilder {
    private Configuration configuration;
    public XMLMapperStatementBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream input) throws Exception {
        Document document = new SAXReader().read(input);
        Element mapperElement = document.getRootElement();
        String namespace = mapperElement.attributeValue("namespace");

        List<Element> statements = mapperElement.selectNodes("//insert | //update | //select | //delete");

        for(Element statement:statements){
            SqlCommandType sqlCommandType = SqlCommandType.valueOf(statement.getQName().getName().toUpperCase());
            String id = statement.attributeValue("id");
            Class<?> parameterType = getClassType(statement.attributeValue("parameterType"));
            Class<?> resultType = getClassType(statement.attributeValue("resultType"));
            String sql = statement.getTextTrim();

            String statementId = namespace+"."+id;
            MappedStatement mappedStatement =  MappedStatement.builder()
                    .id(statementId)
                    .commandType(sqlCommandType)
                    .parameterType(parameterType)
                    .resultType(resultType)
                    .sql(sql)
                    .build();
            configuration.getMappedStatementMap().put(statementId,mappedStatement);
        }
    }

    private Class<?> getClassType(String className) throws ClassNotFoundException {
        return Class.forName(className);
    }
}
